﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace QuanLySieuThi.Models
{
    public class DataAccess
    {
        public static string ConnectionString = "Data Source=BINMTS-PC\\MR_BIN;Initial Catalog=QuanLySieuThi;Integrated Security=True";
        private SqlConnection conn;
        private SqlCommand cmd;
        private SqlDataAdapter adapter;
        private DataTable table;

        public DataAccess()
        {
            conn = new SqlConnection(ConnectionString);
            cmd = new SqlCommand();
            cmd.Connection = conn;
            adapter = new SqlDataAdapter(cmd);
            table = new DataTable();
        }

        public void ExecuteNonQuery(string query, params SqlParameter[] p)
        {
            //Nếu là câu lệnh
            if (query.Contains(" "))
                cmd.CommandType = CommandType.Text;
            else
            {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Clear();
                cmd.Parameters.AddRange(p);
            }

            cmd.CommandText = query;

            conn.Open();
            cmd.ExecuteNonQuery();
            conn.Close();

        }

        public DataTable ExecuteQuery(string query)
        {

            try
            {
                if (query.Contains(" "))
                    cmd.CommandType = CommandType.Text;
                else cmd.CommandType = CommandType.StoredProcedure;
                table.Clear();
                cmd.CommandText = query;
                adapter.Fill(table);
                return table;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                conn.Close();
                return null;
            }
        }
    }
}
